/*
 * sequential_worker.cpp
 *
 *  Created on: 2016年2月25日
 *      Author: Administrator
 */

#include "sequential_task.h"
#include "../single/service.h"
namespace eyas{
namespace thread{

sequential_task::sequential_task()
:active_(false), disposed_(false){
}

sequential_task::~sequential_task() {
	this->dispose();
}
void sequential_task::dispose(){
	boost::mutex::scoped_lock lock(mutex_);
	this->disposed_ = true;
	// 处于活动状态
	if(this->active_){
		// 任务处于活动状态
		this->active_ = false;
		cond_var_.wait(lock);
	}
	while(this->task_queue_.size() > 0){
		this->task_queue_.pop();
	}
}
void sequential_task::sequential_task_proc(){
	this->on_task();
}
void sequential_task::_check_active(){
	if(!this->active_){
		// 未活动
		this->active_ = true;
		eyas::thread::service::instance()->io_service().post(boost::bind(&sequential_task::sequential_task_proc, this->shared_from_this()));
	}
}

void sequential_task::on_task(){
	thread_task_ptr taskPtr;
	{
		boost::mutex::scoped_lock lock(mutex_);
		if(this->task_queue_.size() <= 0){
			return;
		}
		if(!this->active_ || this->disposed_){
			// 任务序列已丧失活跃
			cond_var_.notify_all();
			return;
		}
		taskPtr = this->task_queue_.front();
		this->task_queue_.pop();
	}
	if(nullptr == taskPtr){
		return;
	}
	taskPtr->on_task();
	taskPtr.reset();
	{
		boost::mutex::scoped_lock lock(mutex_);
		if(!this->active_ || this->disposed_){
			// 任务序列已丧失活跃
			cond_var_.notify_all();
			return;
		}
		if(this->task_queue_.size() > 0){
			eyas::thread::service::instance()->io_service().post(boost::bind(&sequential_task::sequential_task_proc, this->shared_from_this()));
		}else{
			// 设置非活跃
			this->active_ = false;
		}
	}
}

}
}
